package org.csu.jpetstore.controller;

import jakarta.servlet.http.HttpSession;
import org.csu.jpetstore.domain.*;
import org.csu.jpetstore.service.CartService;
import org.csu.jpetstore.service.CatalogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.math.BigDecimal;
import java.util.*;

@Controller
@RequestMapping("/cart")
@SessionAttributes(names= {"categories","category"})
public class CartController {

    @Autowired
    private CartService cartService;

    @Autowired
    private CatalogService catalogService;

    @RequestMapping("/getCategories")
    public List<Category> getCategoryList(){
        return catalogService.getCategoryList();
    }

    @RequestMapping("/getProducts")
    public List<Product> getProductList(){
        List<Product> products = new ArrayList<>();
        for(int i = 0;i < getCategoryList().size();i++){
            String categoryId = getCategoryList().get(i).getCategoryId();
            products.addAll(catalogService.getProductListByCategory(categoryId));
        }
        return products;
    }

    @RequestMapping("/getItems")
    public List<Item> getItemList(){
        List<Item> items = new ArrayList<>();
        for(int i = 0;i < getProductList().size();i++){
            String productId = getProductList().get(i).getProductId();
            items.addAll(catalogService.getItemListByProduct(productId));
        }
        return items;
    }

    @GetMapping("/suggestions")
    @ResponseBody
    public List<String> getUsernameSuggestions(@RequestParam String query) {
        List<Category> categories = getCategoryList();
        List<Product> products = getProductList();
        List<Item> items = getItemList();
        Set<String> suggestions = new HashSet<>();

        for (Category category : categories) {
            if (category.getName().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(category.getName());
            }
            if (category.getCategoryId().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(category.getCategoryId());
            }
        }
        for (Product product : products) {
            if (product.getName().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(product.getName());
            }
            if (product.getProductId().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(product.getProductId());
            }
        }
        for (Item item : items) {
            if (item.getItemId().toLowerCase().contains(query.toLowerCase())) {
                suggestions.add(item.getItemId());
            }
        }

        return new ArrayList<>(suggestions);
    }

    // 查看购物车
    @GetMapping("/view")
    public String viewCategories(Model model) {
        List<Category> categories = catalogService.getCategoryList();
        model.addAttribute("categories", categories);
        return "cart/cart";
    }

    @PostMapping("/find")
    public String getCategory(@RequestParam String keyword,Model model) {
        List<Category> categories = getCategoryList();
        List<Product> products = getProductList();
        List<Item> items = getItemList();

        //关键词为总类名
        for (Category category : categories) {
            String str1 = category.getCategoryId();
            String str2 = category.getName();
            boolean condition1 = Objects.equals(str1.toLowerCase(), keyword.toLowerCase());
            boolean condition2 = Objects.equals(str2.toLowerCase(), keyword.toLowerCase());
            if (condition1 || condition2)
                return "redirect:/catalog/category?categoryId=" + str1;
        }

        // 关键词为大类名
        for (Product product : products) {
            String str1 = product.getProductId();
            String str2 = product.getName();
            boolean condition1 = Objects.equals(str1.toLowerCase(), keyword.toLowerCase());
            boolean condition2 = Objects.equals(str2.toLowerCase(), keyword.toLowerCase());
            if (condition1 || condition2)
                return "redirect:/catalog/product?productId=" + str1;
        }

        // 关键词为小类名
        for (Item item : items) {
            String str = item.getItemId();
            if (Objects.equals(str.toLowerCase(), keyword.toLowerCase())) return "redirect:/catalog/item?itemId=" + str;
        }

        String msg = "no find";
        return "redirect:/cart/input?msg="+msg;
    }

    //搜索框
    @GetMapping("/input")
    public String reviseOrder(@RequestParam String msg,Model model){
        model.addAttribute("msg",msg);
        return "cart/input";
    }

    //查看所有大类
    @GetMapping("/allProducts")
    public String viewProducts(Model model) {
        List<Product> products = getProductList();
        model.addAttribute("products", products);
        return "cart/products";
    }

    //查看所有小类
    @GetMapping("/allItems")
    public String viewItems(Model model) {
        List<Item> items = getItemList();
        model.addAttribute("items", items);
        return "cart/items";
    }

    // 总类管理相关方法
    @GetMapping("/category/toAdd")
    public String toAddCategory() {
        return "cart/addCategory";
    }

    @PostMapping("/category/add")
    public String addCategory(@RequestParam String categoryId,
                            @RequestParam String name,
                            @RequestParam String description,
                            @RequestParam double price,
                            Model model) {
        Category category = new Category();
        category.setCategoryId(categoryId);
        category.setName(name);
        category.setDescription(description);
        category.setPrice(price);
        catalogService.addCategory(category);
        return "redirect:/cart/view";
    }

    @GetMapping("/category/toEdit")
    public String toEditCategory(@RequestParam String categoryId, Model model) {
        Category category = catalogService.getCategory(categoryId);
        model.addAttribute("category", category);
        return "cart/editCategory";
    }

    @PostMapping("/category/edit")
    public String editCategory(@RequestParam String categoryId,
                             @RequestParam String name,
                             @RequestParam String description,
                             @RequestParam double price,
                             Model model) {
        Category category = new Category();
        category.setCategoryId(categoryId);
        category.setName(name);
        category.setDescription(description);
        category.setPrice(price);
        catalogService.updateCategory(category);
        return "redirect:/cart/view";
    }

    @GetMapping("/category/delete")
    public String deleteCategory(@RequestParam String categoryId) {
        catalogService.deleteCategory(categoryId);
        return "redirect:/cart/view";
    }

    // 大类管理相关方法
    @GetMapping("/product/toAdd")
    public String toAddProduct(Model model) {
        List<Category> categories = catalogService.getCategoryList();
        model.addAttribute("categories", categories);
        return "cart/addProduct";
    }

    @PostMapping("/product/add")
    public String addProduct(@RequestParam String productId,
                           @RequestParam String name,
                           @RequestParam String description,
                           @RequestParam String categoryId,
                           Model model) {
        Product product = new Product();
        product.setProductId(productId);
        product.setName(name);
        product.setDescription(description);
        product.setCategoryId(categoryId);
        catalogService.addProduct(product);
        return "redirect:/cart/allProducts";
    }

    @GetMapping("/product/toEdit")
    public String toEditProduct(@RequestParam String productId, Model model) {
        Product product = catalogService.getProduct(productId);
        List<Category> categories = catalogService.getCategoryList();
        model.addAttribute("product", product);
        model.addAttribute("categories", categories);
        return "cart/editProduct";
    }

    @PostMapping("/product/edit")
    public String editProduct(@RequestParam String productId,
                            @RequestParam String name,
                            @RequestParam String description,
                            @RequestParam String categoryId,
                            Model model) {
        Product product = new Product();
        product.setProductId(productId);
        product.setName(name);
        product.setDescription(description);
        product.setCategoryId(categoryId);
        catalogService.updateProduct(product);
        return "redirect:/cart/allProducts";
    }

    @GetMapping("/product/delete")
    public String deleteProduct(@RequestParam String productId) {
        catalogService.deleteProduct(productId);
        return "redirect:/cart/allProducts";
    }

    // 小类管理相关方法
    @GetMapping("/item/toAdd")
    public String toAddItem(Model model) {
        List<Product> products = getProductList();
        model.addAttribute("products", products);
        return "cart/addItem";
    }

    @PostMapping("/item/add")
    public String addItem(@RequestParam String itemId,
                         @RequestParam String productId,
                         @RequestParam BigDecimal listPrice,
                         @RequestParam BigDecimal unitCost,
                         @RequestParam int supplierId,
                         @RequestParam String status,
                         @RequestParam String attribute1,
                         @RequestParam String attribute2,
                         @RequestParam String attribute3,
                         @RequestParam String attribute4,
                         @RequestParam String attribute5,
                         @RequestParam int quantity,
                         Model model) {
        Item item = new Item();
        item.setItemId(itemId);
        item.setProductId(productId);
        item.setListPrice(listPrice);
        item.setUnitCost(unitCost);
        item.setSupplierId(supplierId);
        item.setStatus(status);
        item.setAttribute1(attribute1);
        item.setAttribute2(attribute2);
        item.setAttribute3(attribute3);
        item.setAttribute4(attribute4);
        item.setAttribute5(attribute5);
        catalogService.addItem(item,quantity);
        return "redirect:/cart/allItems";
    }

    @GetMapping("/item/toEdit")
    public String toEditItem(@RequestParam String itemId, Model model) {
        Item item = catalogService.getItem(itemId);
        List<Product> products = getProductList();
        model.addAttribute("item", item);
        model.addAttribute("products", products);
        return "cart/editItem";
    }

    @PostMapping("/item/edit")
    public String editItem(@RequestParam String itemId,
                          @RequestParam String productId,
                          @RequestParam BigDecimal listPrice,
                          @RequestParam BigDecimal unitCost,
                          @RequestParam int supplierId,
                          @RequestParam String status,
                          @RequestParam String attribute1,
                          @RequestParam String attribute2,
                          @RequestParam String attribute3,
                          @RequestParam String attribute4,
                          @RequestParam String attribute5,
                          Model model) {
        Item item = new Item();
        item.setItemId(itemId);
        item.setProductId(productId);
        item.setListPrice(listPrice);
        item.setUnitCost(unitCost);
        item.setSupplierId(supplierId);
        item.setStatus(status);
        item.setAttribute1(attribute1);
        item.setAttribute2(attribute2);
        item.setAttribute3(attribute3);
        item.setAttribute4(attribute4);
        item.setAttribute5(attribute5);
        catalogService.updateItem(item);
        return "redirect:/cart/allItems";
    }

    @GetMapping("/item/delete")
    public String deleteItem(@RequestParam String itemId) {
        catalogService.deleteItem(itemId);
        return "redirect:/cart/allItems";
    }
}